package com.tuju.jetpackfirstdemo.data

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.coolweather.coolweatherjetpack.data.model.weather.HeWeather
import com.coolweather.coolweatherjetpack.data.model.weather.Weather
import com.tuju.jetpackfirstdemo.network.CoolWeatherNetwork
import com.tuju.jetpackfirstdemo.utils.CoolWeatherExecutors
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class WeatherRepository private constructor(val network: CoolWeatherNetwork) {

    fun getWeather(weatherId: String, key: String): LiveData<Resource<Weather>> {
        val liveData = MutableLiveData<Resource<Weather>>()
        liveData.postValue(Resource.loading(null))
        //先从本地获取，如果没有再从网络获取，这里可以封装几个策略
        CoolWeatherExecutors.diskIO.execute {
            requestWeather(weatherId, key, liveData)
        }
        return liveData
    }

    fun getBingPic(): LiveData<Resource<String>> {
        val liveData = MutableLiveData<Resource<String>>()
        //直接从网络获取
        CoolWeatherExecutors.diskIO.execute {
            requestBigPic(liveData)
        }
        return liveData
    }


    //请求网路获取天气
    private fun requestWeather(weatherId: String, key: String, liveData: MutableLiveData<Resource<Weather>>) {
        network.fetchWeather(weatherId, key, object : Callback<HeWeather> {
            override fun onFailure(call: Call<HeWeather>, t: Throwable) {
                liveData.postValue(Resource.error("加载失败:" + t.message, null))
            }

            override fun onResponse(call: Call<HeWeather>, response: Response<HeWeather>) {
                CoolWeatherExecutors.diskIO.execute {
                    val weather = response.body()?.weather!![0]
                    liveData.postValue(Resource.success(weather))
                }
            }
        })
    }

    //请求网络获取大图
    private fun requestBigPic(liveData: MutableLiveData<Resource<String>>) {
        network.fetchBingPic(object : Callback<String> {
            override fun onFailure(call: Call<String>, t: Throwable) {
                liveData.postValue(Resource.error("获取图片失败:" + t.message, null))
            }

            override fun onResponse(call: Call<String>, response: Response<String>) {
                CoolWeatherExecutors.diskIO.execute {
                    val picStr = response.body()
                    liveData.postValue(Resource.success(picStr))
                }
            }
        })
    }

    //伴生对象：单例
    companion object {
        private var instance: WeatherRepository? = null

        fun getInstance(network: CoolWeatherNetwork): WeatherRepository {
            if (instance == null) {
                synchronized(WeatherRepository::class.java) {
                    if (instance == null) {
                        instance = WeatherRepository(network)
                    }
                }
            }
            return instance!!
        }
    }

}